package com.cuijq.ms.Iteratordesign.v1;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author by CuiJQ
 * @Classname SnapshotArrayIterator
 * @Description SnapshotArrayIterator Description
 * @Date 2021/5/29 16:47
 *
 * 都要拷贝一份数据到快照中，会增加内存的消耗。如果一个容器同时有多个迭代器在遍历元素，
 * 就会导致数据在内存中重复存储多份。
 * 不过，庆幸的是，Java 中的拷贝属于浅拷贝，也就是说，容器中的对象并非真的拷贝了多份
 */
public class SnapshotArrayIterator<E> implements Iterator {

  private int cursor;
  private ArrayList<E> snapshot;

  public SnapshotArrayIterator(ArrayList arrayList) {
    this.cursor = 0;
    this.snapshot = new ArrayList<>();
    this.snapshot.addAll(arrayList);
  }

  @Override
  public boolean hasNext() {
    return cursor < snapshot.size();
  }

  @Override
  public E next() {
    E currentItem = snapshot.get(cursor);
    cursor++;
    return currentItem;
  }
}

